import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:test_flutter/constant/resources.dart';
import 'package:test_flutter/dio/Api.dart';
import 'package:test_flutter/dio/DioUtil.dart';
import 'package:test_flutter/utils/ColorsUtil.dart';
import 'package:test_flutter/utils/TimerUtil.dart';
import 'package:test_flutter/utils/ToastUtil.dart';
import 'package:test_flutter/utils/common_utils/CustomLocalizations.dart';
import 'package:test_flutter/utils/factory/Fit.dart';
import 'package:test_flutter/widgets/Button.dart';
import 'package:test_flutter/widgets/EditText.dart';

class ModufyPWPage extends StatefulWidget {
  @override
  _ForgetPWPage createState() => new _ForgetPWPage();
}

class _ForgetPWPage extends State<ModufyPWPage> {
  TimerUtil timerCountDown;

  String tip = CustomLocalizations.instance
      .getString(StringIds.verificationCode);
  int stamp;
  bool canClick = true;

  @override
  Widget build(BuildContext context) {
    return new Theme(
        data: new ThemeData(
          primarySwatch: Colors.red,
          brightness: Brightness.light,
        ),
        child: new Scaffold(
          resizeToAvoidBottomPadding: true, //输入框抵住键盘
          backgroundColor: Colors.white,
          appBar: new AppBar(
            centerTitle: true,
            backgroundColor: ColorsUtil.Green,
            title: new Text(CustomLocalizations.instance
                .getString(StringIds.modifyPassWord)),
          ),
          body: new SingleChildScrollView(
            child: new Column(
              children: <Widget>[
                phoneNum,
                new Stack(
                  alignment: new FractionalOffset(0.92, 0.5),
                  children: <Widget>[
                    verifyCode,
                    new GestureDetector(
                      onTap: canClick
                          ? () {
                              _setCodeTip();
                            }
                          : null,
                      child: Container(
                        width: Fit.scaleX(220),
                        height: Fit.scaleX(100),
                        padding: EdgeInsets.only(
                            left: Fit.scaleX(40),
                            top: Fit.scaleX(20),
                            right: Fit.scaleX(40),
                            bottom: Fit.scaleX(20)),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(Fit.scaleX(15)),
                          color: ColorsUtil.Green,
                        ),
                        child: new Center(
                          child: Text(
                            tip,
                            style: new TextStyle(
                                color: Colors.white,
                                fontSize: Fit.scaleTextSize(44)),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                passWord,
                confirmPassWord,
                new Padding(
                  padding: EdgeInsets.only(top: Fit.scaleY(200)),
                  child: new Button(CustomLocalizations.instance
                      .getString(StringIds.confirm), onPressed: setOnclick),
                ),
              ],
            ),
          ),
        ));
  }

  void setOnclick() {
    modifyPassword();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if (timerCountDown != null) timerCountDown.cancel(); //dispose()
  }

  /* 方法定义*/

  void _setCodeTip() {
    if (phoneNum.getValue().length == 0) {
      ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.pleaseEnterUserName));
      return;
    }

    canClick = false;
    timerCountDown = new TimerUtil(mInterval: 1000, mTotalTime: 15 * 1000);
    timerCountDown.setOnTimerTickCallback((int value) {
      int tick = (value ~/ 1000);

      setState(() {
        if (tick == 0) {
          canClick = true;
          tip =CustomLocalizations.instance
              .getString(StringIds.verificationCode);
        } else {
          print(tick);
          tip = tick.toString() + " s";
        }

        //(tick == 0) ? tip = '验证码' : tip = tick.toString() + " s";
      });
    });
    timerCountDown.startCountDown();

    getSmsVerificationCode();
  }

  /*UI 定义*/
  EditText phoneNum = new EditText(CustomLocalizations.instance
      .getString(StringIds.mobilePhoneNumber), 'images/phone.png');
  EditText verifyCode = new EditText(CustomLocalizations.instance
      .getString(StringIds.verificationCode), 'images/code.png');
  EditText passWord = new EditText(CustomLocalizations.instance
      .getString(StringIds.loginPassWord), 'images/password.png');
  EditText confirmPassWord = new EditText(CustomLocalizations.instance
      .getString(StringIds.confirmPassWord), 'images/password.png');

  ///修改密码
  modifyPassword() async {
    if (verifyCode.getValue().length == 0) {
      ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.PleaseGetCode));
      return;
    }

    if (passWord.getValue().length == 0) {
      ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.pleaseEnterPassWord));
      return;
    }

    if (passWord.getValue().length < 6) {
      ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.AtLeast6Bytes));
      return;
    }

    if (confirmPassWord.getValue().length == 0) {
      ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.pleaseEnterPassWord));
      return;
    }

    if (passWord.getValue() != confirmPassWord.getValue()) {
      ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.passwordInconsistent));
      return;
    }

    Map<String, String> requestMap = new Map();
    requestMap['MobileNo'] = phoneNum.getValue();
    requestMap['VerificationCode'] = verifyCode.getValue();
    requestMap['TimeStamp'] = stamp.toString();
    requestMap['NewPassword'] = passWord.getValue();
    requestMap['ConfirmNewPassword'] = confirmPassWord.getValue();


    DioUtil.getInstance(context).post(
        Api.modifyPassword,
            (response) {
          if (response.data['code'] == 1) {
            ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.passwordChangedSuccessfully));
            Navigator.of(context).pop();
          } else {
            ToastUtil.showToast(response.data['msg']);
          }
        },
        data: requestMap,
        hasToken: true,
        errorCallBack: (errorMsg) {
          print("error:" + errorMsg);
          ToastUtil.showToast(errorMsg);
        });

  }

  ///获取验证码
  getSmsVerificationCode() async {
    DioUtil.getInstance(context).get(Api.getSmsVerificationCode + phoneNum.getValue(),
        (response) {
      if (response.data['code'] == 1) {
        stamp = response.data['data']['Stamp'];
        verifyCode.setValue(response.data['data']['VerifyCode']);
      } else {
        ToastUtil.showToast(response.data['msg']);
      }
    }, errorCallBack: (errorMsg) {
      print("error:" + errorMsg);
      ToastUtil.showToast(errorMsg);
    });
  }
}
